#! /usr/bin/perl -w
use strict;

my @err_info_files;
my @searching_files;
@err_info_files = splice(@ARGV,0,1);

@searching_files = splice(@ARGV,0);

my $err_file_num = @err_info_files;
my $searching_file_num = @searching_files;
print "err files num is $err_file_num\n";
print "searching files num is $searching_file_num\n";

foreach (@err_info_files) {
	if (! open ERR_FILE ,'<',$_){
		die "Cannot open $_:$!";	
	}
	my $result_fh;
	if(! open $result_fh,'>',"result_$_"){
		die "Cannot open file $_\_result.txt:$!";
	}
	while ( <ERR_FILE> ){
		print $result_fh "matching word is $_\n";
		&search_line_in_files($_,$result_fh, @searching_files);
	}
	close ERR_FILE;
	close $result_fh;
	
}

sub search_line_in_files {
	my @line = split / /,$_[0];
	my $result_fh = $_[1];
	my @files = splice @_,2;
	my $match_word;
	my $search_fh;
	foreach (@files){
		my $cur_filename = $_;
		if(! open $search_fh,'<',$_){
			die "Cannot open file $_:$!";
		}
		my $first_match_word = $line[0];

		my @base_lines = &grep_word_in_file($first_match_word,$search_fh);

		foreach (@line){
			&grep_word_in_array($_, \@base_lines);
		}
		print $result_fh "$cur_filename",":have found ",scalar @base_lines," matched.\n";
		if(@base_lines > 0){
			&write_array_to_file(\@base_lines,$result_fh);
		}

		print $result_fh "\n\n";
		close $search_fh;
	}
}

sub grep_word_in_file {
	my $word = $_[0];
	my $file_fh = $_[1];
	my @matched_lines;
	seek $file_fh,0,0;
	
	while( <$file_fh> ){
		if(m/$word/){
			push @matched_lines,$_;
		}
	}
	return @matched_lines;
}

sub grep_word_in_array {
	my $word;
	my $grep_lines;
	my $tmp_line;
	my @ret_lines;
	($word,$grep_lines) = @_;
#	print "grep_word_in_array: ",@$grep_lines,"\n";
	while( $tmp_line = shift @$grep_lines ){
		if($tmp_line =~ m/$word/){
			push @ret_lines,$tmp_line;
		}
	}
	@$grep_lines = @ret_lines;
}

sub write_array_to_file {
	my $array_ref;
	my $file_fh;
	my $tmp_line;
	($array_ref,$file_fh) = @_;

	while ($tmp_line = shift @$array_ref){
		print $file_fh "$tmp_line";
	}

}

